# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import datetime
import random
import re

from wenlincms import template

register = template.Library()

"""本文件放一些基础 template_tags"""


# 过滤数字，隐藏末尾几位
@register.filter(name="elint")
def elint(v, n):
    try:
        a = str(int(float(v)))
        if len(a) > n:
            return int(a[:-n]) * 10 ** n
        else:
            return a
    except Exception:
        return v


# 过滤数字，只显示首位，其他用*
@register.filter(name="elint2")
def elint2(v):
    try:
        a = str(int(float(v)))
        return a[:1] + '*' * (len(a) - 1)
    except Exception:
        return v


# 过滤数字，只显示首位，其他用0，末尾无加号，在fig中用
@register.filter(name="elint3")
def elint3(v):
    try:
        a = str(int(float(v)))
        if a[0] == '-':
            return a[:2] + '0' * (len(a) - 2)
        else:
            return a[:1] + '0' * (len(a) - 1)
    except Exception:
        return v


# 渲染url类型，返回带http的全连接
@register.filter(name="elfullurl")
def elfullurl(v):
    if v == '' or v is None or v == 'None':
        return ''
    else:
        u = re.sub(r'^https?\:\/\/(.+)$', r'\1', v)
        return 'http://' + u


# 如果为空，则显示为“未知”等
@register.filter(name="elweizhi")
def elweizhi(v, i=0):
    dic = ['-', '暂无', 'xx', '不限', '**', '0', '未知单位', '', '全国', '未知', ]
    if v == '' or v == 'None' or v is None:
        return dic[i]
    else:
        return v


# 过滤bool类型
@register.filter(name="elbool")
def elbool(v):
    if v is None:
        return "-"
    elif v:
        return "是"
    return "否"


# 过滤timestamp类型到datetime类型
@register.filter(name="eltimestamp")
def eltimestamp(v):
    try:
        ts = float(v)
    except ValueError:
        return None
    return datetime.datetime.fromtimestamp(ts)


# 过滤风报的日期类型
@register.filter(name="elfbztbdate")
def elfbztbdate(v):
    return v[:10]


# 过滤浮点型数字，去除首尾的0，保留末尾n位
@register.filter(name="elfloat")
def elfloat(v, n):
    try:
        v = str(v)
        v1 = v.split(".")[0]
        v0 = v.split(".")[1]
        return v1 + "." + v0[:n]
    except Exception:
        return v


# 根据企业名称获取企业对象
@register.as_tag
def elcombytitle(title):
    from wlmodels.company.models import ELPost
    return ELPost.get_company_by_title(title)


# 过滤信用评分，有缺失的话用默认值填补
@register.filter(name="eldefault")
def eldefault(v, n):
    try:
        if v:
            v = int(v)
            if v > 0:
                return v
        if n == "random":
            return random.randint(52, 72)
        else:
            return n
    except ValueError:
        if n == "random":
            return random.randint(32, 42)
        else:
            return n
